let _width = $(window).width();
let _height = $(window).height();
let width = 0.9 * _width;
let height = 0.96 * _height;

let x_attr = 'name';
let fontFamily;
let categories;

function set_ui() {
    // 设置字体
    let ua = navigator.userAgent.toLowerCase();
    fontFamily = "Khand-Regular";
    if (/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)) {
        fontFamily = "PingFangSC-Regular";
    }
    d3.select("body")
        .style("font-family", fontFamily);
}

function draw_main() {
    let padding = {'left': 0.2*width, 'bottom': 0.1*height, 'top': 0.2*height, 'right': 0.1*width};
    let svg = d3.select('#container')
        .select('svg')
        .attr('width', width)
        .attr('height', height);

    // title
    svg.append('g')
        .attr('transform', `translate(${padding.left+(width-padding.left-padding.right)/2}, ${padding.top*0.4})`)
        .append('text')
        .attr('class', 'title')
        .text('Stacked Bar Chart for Population by Age and State in America');

    // x axis - state
    let x_values = get_set(data, x_attr);
    let x = d3.scaleBand()
        .domain(x_values)
        .range([padding.left, width-padding.right])
        .paddingInner(0.1);    
    let axis_x = d3.axisBottom()
        .scale(x)
        .ticks(x_values.length)
        .tickFormat(d => d);

    // y axis - population
    let y = d3.scaleLinear()
        .domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
        .range([height-padding.bottom, padding.top]);    
    let axis_y = d3.axisLeft()
        .scale(y)
        .ticks(10)
        .tickFormat(d3.format('~s'));

    // x axis
    svg.append('g')
        .attr('transform', `translate(${0}, ${height-padding.bottom})`)
        .call(axis_x)
        .attr('font-family', fontFamily)
        .attr('font-size', '0.8rem')

    svg.append('g')
        .attr('transform', `translate(${padding.left+(width-padding.left-padding.right)/2}, ${height-padding.bottom})`)
        .append('text')
        .attr('class', 'axis_label')
        .attr('dx', '-0.4rem')
        .attr('dy', 0.08*height)
        .text('State');

    // y axis
    svg.append('g')        
        .attr('transform', `translate(${padding.left}, ${0})`)
        .call(axis_y)
        .attr('font-family', fontFamily)
        .attr('font-size', '0.8rem')
    svg.append('g')
        .attr('transform', `
            translate(${padding.left}, ${height/2})
            rotate(-90)    
        `)
        .append('text')
        .attr('class', 'axis_label')
        .attr('dy', -height*0.07)
        .text('Population');

    // color scheme
    let color = d3.scaleOrdinal()
        .domain(categories)
        .range(d3.schemeSpectral[series.length]);

    // bars
    svg.append('g')
        .selectAll('g')
        .data(series)
        .enter().append('g')
        .attr('fill', d => color(d.key))
        .selectAll('rect')
        .data(d => d)
        .enter().append('rect')
        .attr('x', d => x(d.data.name))
        .attr('y', d => y(d[1]))
        .attr('width', x.bandwidth())
        .attr('height', d => y(d[0])-y(d[1]))

    // color legend
    rect_width = width*0.03;
    rect_height = rect_width/3;
    legend = svg.append('g')
        .attr('transform', `translate(${width-padding.right-rect_width*series.length}, ${padding.top})`);

    g = legend.selectAll('g')
        .data(series.map(d => d.key))
        .enter().append('g')
        .attr('transform', (d, i) => `translate(${i*rect_width},${0})`);
        
    g.append('rect')
        .attr('width', rect_width-1)
        .attr('height', rect_height)
        .attr('fill', d => color(d));
    g.append('line')
        .attr('x1', rect_width/2)
        .attr('y1', rect_height)
        .attr('x2', rect_width/2)
        .attr('y2', rect_height*1.3)
        .attr('stroke', 'black');
    g.append('text')
        .attr('x', rect_width/2)
        .attr('y', rect_height*2.1)
        .attr('text-anchor', 'middle')
        .attr('font-size', '0.7rem')
        .text(d => d);

    legend.append('text')
        .attr('dy', '-0.3rem')
        .attr('font-weight', 'bold')
        .attr('font-size', '0.7rem')
        .text('Age (years)');
}

function main() {
    d3.csv(data_file).then(function(DATA) {
        data = DATA;
        categories = data.columns.slice(1);
        data.forEach(d => {
            let sum = 0;
            categories.forEach(c => {
                sum += parseInt(d[c]);
            })
            d.sum = sum;
        })
        data = data.sort((a, b) => b.sum-a.sum);

        let stack = d3.stack()
            .keys(categories);
        series = stack(data)
        //.map(d => (d.forEach(v => v.key = d.key), d)); // how to understand this sentence ?

        console.log('series', series);
        set_ui();
        draw_main();
    })
}

main()